package com.bw.gateway.filter;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.bw.gateway.config.IgnoreWhiteProperties;
import com.bw.gateway.util.Result;


import com.ruoyi.common.core.utils.JwtUtils;
import io.micrometer.core.instrument.binder.http.HttpServletRequestTagsProvider;
import lombok.SneakyThrows;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.netty.http.server.HttpServerRequest;
import reactor.netty.http.server.HttpServerResponse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;

//@Component
public class LoginFilter implements GlobalFilter, Order {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IgnoreWhiteProperties ignoreWhite;
    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String url = request.getURI().getPath();
        // 跳过不需要验证的路径
        if (ignoreWhite.getWhites().contains(url))
        {
            return chain.filter(exchange);
        }
        String token = exchange.getRequest().getHeaders().getFirst("Token");
        boolean blank = StringUtils.isBlank(token);
        Boolean aBoolean = redisTemplate.hasKey("login:"+token);
        if(StringUtils.isBlank(token) || !redisTemplate.hasKey("login:"+token)){
            // 错误，需要拦截，设置状态码
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        try {
            JwtUtils.parseToken(token);
        }catch (Exception e){
            // 错误，需要拦截，设置状态码
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }


    @Override
    public int value() {
        return 0;
    }

    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }
}
